package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.admin.util.QiNiuUploadUtil;
import cn.wolfcode.trip.admin.util.UploadUtil;
import cn.wolfcode.trip.base.domain.Item;
import cn.wolfcode.trip.base.query.ItemQueryObject;
import cn.wolfcode.trip.base.service.IItemCatalogService;
import cn.wolfcode.trip.base.service.IItemService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("item")
public class ItemController {


    @Autowired
    private IItemService itemService;
    @Autowired
    private IItemCatalogService catalogService;
    // 待审核游记列表
    @RequestMapping("list")
    public String list(Model model , @ModelAttribute("qo") ItemQueryObject qo){
        PageInfo result = itemService.query(qo);
        model.addAttribute("result",result);
        model.addAttribute("catalogs",catalogService.selectAll());
        return "item/list";
    }

    /**
     * 删除商品
     * @param
     * @return
     */
    @RequestMapping("delete")
    @ResponseBody
    public JSONResult delete(Long itemId){
        JSONResult result = new JSONResult();
        try {
            if(itemId != null){
                itemService.delete(itemId);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JSONResult saveOrUpdate(Item item, MultipartFile file){
        JSONResult result = new JSONResult();
        try {
            if(file != null && file.getSize() > 0){
                // 将图片上传到图片服务器
                String imgUrl = QiNiuUploadUtil.upload(file, UploadUtil.BASE_PATH + "upload");
                item.setImageUrl(imgUrl);
            }
            itemService.saveOrUpdate(item);

        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

}
